<template>
  <div class="addGoods">
    <headTop></headTop>
    <el-row style="margin-top: 20px">
      <el-col :span="14" :offset="4">
        <header class="form_header">选择食品种类</header>
        <el-form
          :model="ruleForm"
          ref="ruleForm"
          label-width="110px"
          class="form"
        >
          <el-row class="category_select">
            <el-form-item label="食品种类">
              <el-select
                v-model="ruleForm.categorySelect"
                style="width: 100%"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in ruleForm.categoryList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-row>
          <el-row
            class="add_category_row"
            :class="showAddCategoty ? 'showEdit' : ''"
          >
            <div class="add_category">
              <el-form-item label="食品种类" prop="name">
                <el-input v-model="ruleForm.name"></el-input>
              </el-form-item>
              <el-form-item label="种类描述">
                <el-input v-model="ruleForm.description"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitcategorFrom('ruleForm')"
                  >提交</el-button
                >
              </el-form-item>
            </div>
          </el-row>
          <div class="add_category_button" @click="addCategoryFun">
            <i class="el-icon-caret-top edit_icon" v-if="showAddCategoty"></i>
            <i class="el-icon-caret-bottom edit_icon" v-else slot="icon"></i>
            <span>添加食品种类</span>
          </div>
        </el-form>

        <header class="form_header">添加食品</header>
        <el-form
          :rules="foodrules"
          ref="foodForm"
          :model="foodForm"
          label-width="110px"
          class="form food_form"
        >
          <el-form-item label="食品名称" prop="name">
            <el-input v-model="foodForm.name"></el-input>
          </el-form-item>
          <el-form-item label="食品活动">
            <el-input v-model="foodForm.activity"></el-input>
          </el-form-item>
          <el-form-item label="食品详情">
            <el-input v-model="foodForm.description"></el-input>
          </el-form-item>
          <el-form-item label="上传食品图片">
            <el-upload
              class="avatar-uploader"
              :action="baseUrl + '/v1/addimg/food'"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="foodForm.image_path"
                :src="baseImgPath + foodForm.image_path"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="食品特点">
            <el-select
              v-model="foodForm.attributes"
              multiple
              placeholder="请选择活动区域"
            >
              <el-option
                v-for="item in attributes"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="食品规格">
            <el-radio-group v-model="foodSpecs">
              <el-radio label="one">单规格</el-radio>
              <el-radio label="more">多规格</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- ===== -->
          <el-row v-if="foodSpecs == 'one'">
            <el-form-item label="包装费">
              <el-input-number
                v-model="foodForm.specs[0].packing_fee"
                @change="handleChange"
                :min="0"
                :max="100"
                size="mini"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="价格">
              <el-input-number
                v-model="foodForm.specs[0].price"
                @change="handleChange"
                :min="0"
                :max="10000"
                size="mini"
              ></el-input-number>
            </el-form-item>
          </el-row>

          <el-row v-else style="overflow: auto; text-align: center">
            <el-button
              @click="dialogFormVisible = !dialogFormVisible"
              type="primary"
              style="margin-bottom: 10px"
              >添加规格</el-button
            >
            <el-table
              :cell-style="{ textAlign: 'center' }"
              :header-cell-style="{
                color: 'black',
                background: '#eef1f6',
                textAlign: 'center',
              }"
              :data="foodForm.specs"
              style="width: 100%"
            >
              <el-table-column prop="specs" label="规格"> </el-table-column>
              <el-table-column prop="packing_fee" label="包装费" width="180">
              </el-table-column>
              <el-table-column prop="price" label="价格"> </el-table-column>
              <el-table-column label="操作" width="180">
                <template slot-scope="specs">
                  <el-button
                    type="danger"
                    size="mini"
                    @click="handleDelete(specs)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-row>
          <el-form-item style="margin-top: 10px">
            <el-button type="primary" @click="addFood('foodForm')"
              >确认添加食品</el-button
            >
          </el-form-item>
        </el-form>

        <!--添加规格对话框  -->
        <el-dialog title="添加规格" :visible.sync="dialogFormVisible">
          <el-form ref="specsForm" :rules="specsFormules" :model="specsForm">
            <el-form-item label="规格" prop="specs" label-width="100px">
              <el-input v-model="specsForm.specs"></el-input>
            </el-form-item>
            <el-form-item label="包装费" label-width="100px">
              <el-input-number
                v-model="specsForm.packing_fee"
                @change="handleChange"
                :min="0"
                :max="100"
                size="mini"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="价格" label-width="100px">
              <el-input-number
                v-model="specsForm.price"
                @change="handleChange"
                :min="0"
                :max="10000"
                size="mini"
              ></el-input-number>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="addspecs('specsForm')"
              >确 定</el-button
            >
          </div>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import headTop from "../components/headTop";
import { getCategory, addCategry, addFoods } from "../api/getData";
import { baseUrl, baseImgPath } from "../config/env";
export default {
  data() {
    return {
      // 图片
      baseUrl,
      baseImgPath,
      // 当前餐馆ID
      restaurantId: 1,
      // 食品种类
      ruleForm: {
        categoryList: [],
        name: "",
        categorySelect: "",
        description: "",
      },
      // 是否显示添加食品种类
      showAddCategoty: false,
      // ==========
      foodForm: {
        name: "",
        description: "",
        image_path: "",
        activity: "",
        attributes: [],
        specs: [
          {
            specs: "默认",
            packing_fee: 0,
            price: 20,
          },
        ],
      },
      // 规格
      foodSpecs: "one",
      // 食品规格
      specsForm: {
        specs: "",
        packing_fee: 0,
        price: 20,
      },
      // 食品特点
      attributes: [
        {
          value: "新",
          label: "新品",
        },
        {
          value: "招牌",
          label: "招牌",
        },
      ],
      // 规格验证
      specsFormules: {
        specs: [{ required: true, message: "请输入规格", trigger: "blur" }],
      },
      // 食品名称验证
      foodrules: {
        name: [{ required: true, message: "请输入食品名称", trigger: "blur" }],
      },
      dialogFormVisible: false,
    };
  },
  // 路由守卫
  beforeRouteEnter: (to, from, next) => {
    // console.log(to);
    if (from.path != "/shopList" && to.query.restaurantId == undefined) {
      // console.log(888888888);
      // console.log(to.query.restaurant_id);
      next((vm) => {
        vm.restaurant_id = Math.ceil(Math.random() * 10);
        vm.$msgbox({
          title: "提示",
          message: "添加食品需要选择一个商铺，先去选择一个商铺吧！",
          showCancelButton: true,
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          beforeClose: (action, instance, done) => {
            if (action === "confirm") {
              vm.$router.push("/shopList");
              done();
            } else {
              vm.$message({
                showClose: true,
                message: "这是一条消息提示",
              });
              done();
            }
          },
        });
      });
    } else {
      next((vm) => {
        console.log(vm.$route.query.restaurantId);
        vm.restaurantId = vm.$route.query.restaurantId;
      });
    }
  },
  created() {
    this.initData();
  },
  components: {
    headTop,
  },
  methods: {
    async initData() {
      try {
        // 获取当前商品种类
        console.log(this.restaurantId);
        const { data } = await getCategory(this.restaurantId);
        if (data.status == 1) {
          data.category_list.map((item, index) => {
            item.value = index;
            item.label = item.name;
          });
          this.ruleForm.categoryList = data.category_list;
        } else {
          console.log(data);
        }
        console.log("商品种类====", data);
      } catch (err) {
        console.log(err);
      }
    },
    // 提交食品种类
    submitcategorFrom(ruleForm) {
      console.log("提交食品种类==", ruleForm);
      this.$refs[ruleForm].validate(async (valid) => {
        if (valid) {
          const params = {
            name: this.ruleForm.name,
            description: this.ruleForm.description,
            restaurant_id: this.restaurantId,
          };
          try {
            const res = await addCategry(params);
            console.log("添加食品种类==", res);
            if (res.status == 1) {
              this.initData();
              this.ruleForm.name = "";
              this.ruleForm.description = "";
              this.showAddCategoty = false;
              this.$message({
                type: "succcess",
                message: "添加成功",
              });
            } else {
              this.$message({
                type: "error",
                message: res.message,
              });
            }
          } catch (err) {
            console.log(err);
          }
        } else {
          this.$notify.error({
            title: "错误",
            message: "请检查输入是否正确",
            offset: 100,
          });
          return false;
        }
      });
    },
    // 显示食品种类
    addCategoryFun() {
      this.showAddCategoty = !this.showAddCategoty;
    },
    // 添加规格
    async addspecs(specsForm) {
      try {
        await this.$refs[specsForm].validate();
        this.foodForm.specs.push({ ...this.specsForm });
        this.specsForm.specs = "";
        this.specsForm.packing_fee = 0;
        this.specsForm.price = 20;
        this.dialogFormVisible = false;
      } catch (err) {
        console.log(err);
      }
    },
    // 删除规格
    handleDelete(specs) {
      console.log("删除规格:", specs);
      this.foodForm.specs.splice(specs.$index, 1);
    },
    // 确认上传食品
    async addFood(foodForm) {
      try {
        console.log(typeof this.ruleForm.categorySelect);
        if (typeof this.ruleForm.categorySelect != "string") {
          await this.$refs[foodForm].validate();
          const categoryId = this.ruleForm.categoryList[
            this.ruleForm.categorySelect
          ].id;
          console.log(categoryId);
          const params = {
            ...this.foodForm,
            category_id: this.categoryId,
            restaurant_id: this.restaurantId,
          };
          const res = await addFoods(params);
          if (res.status == 1) {
            this.$message({
              type: "success",
              message: "添加成功",
            });
            // 重置表单
            this.foodForm = {
              name: "",
              description: "",
              image_path: "",
              activity: "",
              attributes: [],
              specs: [
                {
                  specs: "默认",
                  packing_fee: 0,
                  price: 20,
                },
              ],
            };
          } else {
            this.$message({
              type: "error",
              message: res.message,
            });
          }
          console.log(res);
        } else {
          this.$message({
            type: "error",
            message: "请选择食品种类",
          });
        }
      } catch (err) {
        console.log(err);
      }
    },
    // 图片上传
    handleAvatarSuccess(res, file) {
      console.log("图片上传-res", res);
      console.log("图片上传-file", file);
      if (res.status == 1) {
        this.foodForm.image_path = res.image_path;
      } else {
        this.$message({
          type: "error",
          message: "图片上传失败",
        });
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    handleChange(value) {
      console.log(value);
    },
  },
};
</script>

<style lang="less" >
@import "../style/mixin.less";
.el-table {
  border: 1px solid #b6bec5;
  .el-table-column {
    height: 30px;
  }
}
.addGoods {
  .form_header {
    text-align: center;
    margin-bottom: 10px;
  }
  .form {
    min-width: 400px;
    margin-bottom: 30px;
    &:hover {
      box-shadow: 0 0 8px 0 rgba(232, 237, 250, 0.6),
        0 2px 4px 0 rgba(232, 237, 250, 0.5);
      border-radius: 6px;
      transition: all 400ms;
    }
    .category_select {
      border: 1px solid #eaeefb;
      padding: 10px 30px 10px 10px;
      border-top-right-radius: 6px;
      border-top-left-radius: 6px;
    }
    .add_category_row {
      height: 0px;
      overflow: hidden;
      transition: all 400ms;
      background: #f9fafc;
      .add_category {
        background: #f9fafc;
        padding: 10px 30px 0px 10px;
        border: 1px solid #eaeefb;
        border-top: none;
      }
    }
    .showEdit {
      height: 185px;
    }
    .add_category_button {
      text-align: center;
      line-height: 40px;
      border-bottom-right-radius: 6px;
      border-bottom-left-radius: 6px;
      border: 1px solid #eaeefb;
      border-top: none;
      cursor: pointer;
      &:hover {
        background: #f9fafc;
        span,
        .edit_icon {
          color: #20a0ff;
        }
      }
      span {
        .sc(14px,#999);
        transition: all 400ms;
      }
      .edit_icon {
        color: #cccccc;
        font-size: 20px;
        transition: all 400ms;
      }
    }
  }
  .food_form {
    border: 1px solid #eaeefb;
    padding: 10px 10px 0;
  }
}
.el-tag.el-tag--info {
  color: #409eff;
}
// 图片上传
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>